package com.sgy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sgy.ClientFilterUrlMgt;
import com.sgy.entity.ClientFilterUrl;
import com.sgy.mapper.ClientFilterUrlMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author shenguangyang
 * @date 2022-08-14 8:41
 */
@RestController
@RequestMapping("/client")
public class ClientController {
    @Resource
    private ClientFilterUrlMapper clientFilterUrlMapper;

    /**
     * 重定向地址: 如果是本地文件必须是file:///D:/xxx/info.html 格式
     * @param clientFilterUrl
     * @return
     */
    @PostMapping("/url/filter/save")
    public String add(@RequestBody ClientFilterUrl clientFilterUrl) {
        synchronized (this){
            String url = clientFilterUrl.getUrl();
            if (url == null || "".equals(url)) {
                return "url不能为空";
            }
            LambdaQueryWrapper<ClientFilterUrl> qw = new LambdaQueryWrapper<>();
            qw.eq(ClientFilterUrl::getUrl, clientFilterUrl.getUrl());
            ClientFilterUrl clientFilterUrlFromDb = clientFilterUrlMapper.selectOne(qw);

            if (clientFilterUrlFromDb != null) {
                clientFilterUrl.setId(clientFilterUrlFromDb.getId());
                clientFilterUrlMapper.updateById(clientFilterUrlFromDb);
            } else {
                clientFilterUrlMapper.insert(clientFilterUrl);
            }
            ClientFilterUrlMgt.add(clientFilterUrl);
            return "ok";
        }
    }

    @GetMapping("/exit")
    public String exit() {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.exit(1);
        }).start();
        return "客户端 5s 之后退出";
    }
}
